<!--描述：预约卸货-->
<template>
	<div class="m-window m-view-appointmentListS">
		<div class="m-condition m-appointmentListS-condition">
			<el-row :gutter="5">
				<el-form
					ref="headerRuleForm"
					label-width="70px"
					:inline-message="true"
					label-position="left"
					class="m-headerForm"
				>
					<el-col :span="4">
						<el-form-item label="车号" class="rightItem">
							<el-input v-model="carNum" type="text" placeholder="车牌号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<el-form-item class="rightItem" label="预约日期">
							<el-date-picker
								v-model="startDate"
								type="date"
								placeholder="选择开始日期"
								value-format="yyyy-MM-dd"
								clearable
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="3">
						<el-date-picker
							v-model="endDate"
							type="date"
							placeholder="选择结束日期"
							value-format="yyyy-MM-dd"
							clearable
						></el-date-picker>
					</el-col>
					<el-col :span="4">
						<el-form-item label="状态" class="rightItem">
							<el-select placeholder="状态" v-model="state" clearable>
								<el-option
									v-for="(item,index) in appointStateItem"
									:key="index"
									:label="item.name"
									:value="item.code"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="2" :offset="1">
						<el-button @click="queryAppointList(1)" type="primary" :disabled="queryDisabled">查询</el-button>
					</el-col>
					<el-col :span="2">
						<el-button @click="addAppointList" type="primary" :disabled="appiontDisabled">预约</el-button>
					</el-col>
					<el-col :span="2">
						<el-button @click="checkAppoint" type="primary" :disabled="checkAppointDisabled">编辑</el-button>
					</el-col>
					<el-col :span="2">
						<el-button @click="cancelAppoint" type="primary" :disabled="cancelAppointDisabled">取消</el-button>
					</el-col>
				</el-form>
			</el-row>
		</div>
		<!-- 表格数据 -->
		<div class="m-agTable m-bottom">
			<ag-grid-vue
				class="ag-theme-balham ag-table"
				:gridOptions="gridOptions"
				:columnDefs="columnDefs"
				:rowData="rowData"
				v-loading="loading"
				@rowDoubleClicked="rowDoubleClickedShow"
			></ag-grid-vue>
		</div>
		<!-- 分页 -->
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				@prev-click="handlePrevClick"
				@next-click="handleNextClick"
				:current-page="currentPage"
				:page-sizes="[30,50,100,150,200]"
				:page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalPage"
			></el-pagination>
		</div>
		<!-- 弹出框 -->
		<el-dialog
			width="70%"
			class="m-appointDialog"
			:title="dialogTitle"
			:before-close="dialogCancel"
			:visible.sync="dialogFormVisible"
			v-dialogDrag
		>
			<div class="m-appointFormDialog">
				<el-form :model="appointform" label-width="120px" :rules="rules" ref="appointform">
					<el-row>
						<el-col :span="12">
							<el-form-item label="送货单号" prop="deliveryNo">
								<el-input
									v-model.trim="appointform.deliveryNo"
									placeholder="请输入送货单号"
									@change="getPurOrderInfo"
									@clear="purchaseOrderClear"
									maxlength="15"
									clearable
								></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="采购订单" prop="purchaseOrderNo">
								<el-input
									v-model="appointform.purchaseOrderNo"
									placeholder="请输入采购订单"
									@change="purchaseOrderChange"
									disabled
								></el-input>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row>
						<el-col :span="12">
							<el-form-item label="供应商" prop="supplierName">
								<el-input v-model="appointform.supplierName" placeholder="供应商" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="送货公司" prop="companyName">
								<el-input v-model="appointform.companyName" placeholder="送货公司" disabled></el-input>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row>
						<el-col :span="12">
							<el-form-item label="送货区域" prop="unloadingPlace">
								<el-select
									v-model="appointform.unloadingPlace"
									placeholder="送货区域"
									@change="addressChange"
									clearable
								>
									<el-option
										v-for="(item,index) in deliverAreaItem"
										:key="index"
										:value="item.unloadAddree"
										:label="item.unloadAddree"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="物料名称" prop="matName">
								<el-input v-model="appointform.matName" placeholder="物料名称" disabled></el-input>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row>
						<el-col :span="12">
							<el-form-item label="区域联系人" prop="linkMan">
								<el-select v-model="appointform.linkMan" placeholder="区域联系人" clearable>
									<el-option
										v-for="(item,index) in areaLinkMans"
										:key="index"
										:value="item.linkman"
										:label="item.linkman"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
               <!-- v-show="dialogTitle=='预约'" -->
							<el-form-item label="订单剩余数量" prop="remainQty">
								<el-input v-model="appointform.remainQty" placeholder="订单剩余数量" disabled></el-input>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row>
						<el-col :span="12">
							<el-form-item label="批次" prop="batch">
								<el-input v-model="appointform.batch" placeholder="批次" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="预约日期" prop="appointmentDate">
								<el-date-picker
									v-model="appointform.appointmentDate"
									type="date"
									placeholder="预约日期"
									value-format="yyyy-MM-dd"
                  @change="transportTypeChange"
									clearable
								></el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row>
						<el-col :span="12">
							<el-form-item label="送货车号" prop="carNum">
								<el-input v-model="appointform.carNum" placeholder="送货车号" disabled></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="运输方式" prop="transport">
								<el-select
									v-model="appointform.transport"
									placeholder="运输方式"
									clearable
									@change="transportTypeChange"
								>
									<el-option
										v-for="(item,index) in transportTypeItem"
										:key="index"
										:value="item"
										:label="item"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
          
					<el-row>
						<el-col :span="12">
							<el-form-item label="预约时段" prop="appointmentPeriod">
								<el-select v-model="appointform.appointmentPeriod" placeholder="预约时段" clearable
									@change="transportTypeChange">
									<el-option
										v-for="(item,index) in appointTimeItem"
										:key="index"
										:value="item"
										:label="item"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="联系人" prop="driver">
								<el-input v-model="appointform.driver" placeholder="联系人"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item label="送货数量" prop="quantity">
								<el-input type="Number"
                  v-model="appointform.quantity" placeholder="送货数量(公斤)"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="联系电话" prop="driverPhone">
								<el-input v-model="appointform.driverPhone" placeholder="联系电话"></el-input>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row v-if="appointform.transport=='集装箱'">
						<el-col :span="12">
							<el-form-item label="柜型" prop="cabinetType">
								<el-select v-model="appointform.cabinetType" placeholder="柜型" @change="cabinetTypeChange">
									<el-option
										v-for="(item,index) in cabinetTypeItem"
										:key="index"
										:value="item"
										:label="item"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="柜号数量" prop="cabinetQty">
								<el-input v-if="appointform.cabinetType == '40HQ'" v-model="appointform.cabinetQty" placeholder="柜号数量(不能大于2)" disabled></el-input>
								<el-input v-else v-model="appointform.cabinetQty" placeholder="柜号数量(不能大于2)" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="appointform.cabinetQty>=1">
							<el-form-item label="柜号1" prop="cabinetNo1">
								<el-input v-model="appointform.cabinetNo1" placeholder="柜号(4位大写字码+7位数字)" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="appointform.cabinetQty>=2">
							<el-form-item label="柜号2" prop="cabinetNo2">
								<el-input v-model="appointform.cabinetNo2" placeholder="柜号(4位大写字码+7位数字)" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row v-if="appointform.transport=='铁路'">
						<el-col :span="12">
							<el-form-item label="卡号数量" prop="cartQty">
								<el-input v-model="appointform.cartQty" placeholder="卡号数量(不能大于6)" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="appointform.cartQty>=1">
							<el-form-item label="卡号1" prop="cartNo1">
								<el-input v-model="appointform.cartNo1" type="Number" placeholder="卡号(7位数字)" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="appointform.cartQty>=2">
							<el-form-item label="卡号2" prop="cartNo2">
								<el-input v-model="appointform.cartNo2" type="Number" placeholder="卡号(7位数字)" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="appointform.cartQty>=3">
							<el-form-item label="卡号3" prop="cartNo3">
								<el-input v-model="appointform.cartNo3" type="Number" placeholder="卡号(7位数字)" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="appointform.cartQty>=4">
							<el-form-item label="卡号4" prop="cartNo4">
								<el-input v-model="appointform.cartNo4" type="Number" placeholder="卡号(7位数字)" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="appointform.cartQty>=5">
							<el-form-item label="卡号5" prop="cartNo5">
								<el-input v-model="appointform.cartNo5" type="Number" placeholder="卡号(7位数字)" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="appointform.cartQty>=6">
							<el-form-item label="卡号6" prop="cartNo6">
								<el-input v-model="appointform.cartNo6" type="Number" placeholder="卡号(7位数字)" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogCancel">取 消</el-button>
				<el-button type="primary" @click="dialogSubmit" :disabled="comfirmDisabled">保 存</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>

import gridOptions from "lesso-common/public/gridOptions"
import _Api from "@/api";
/**
 * @group appointmentListS
 * 预约卸货
*/
export default {
	name: "appointmentListS",
	data () {
		let checkCarNo = (rule, value, callback) => {
			let xreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/;  //新能源车牌（8位）
			let creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;    //非新能源车牌（7位）
			if (!xreg.test(value) && !creg.test(value)) {
				callback(new Error("请输入正确车号！"));
			}
			callback();
		};
		let checkPhone = (rule, value, callback) => {
			let phoneRule = /^((1)+\d{10})$/;
			if (!phoneRule.test(value)) {
				callback(new Error("请输入正确手机号码！"));
			}
			callback();
		};
		let checkQty = (rule, value, callback) => {
			if (value > Number(this.appointform.remainQty)) {
				callback(new Error("送货数量不能大于订单剩余数量"));
			} else if (value > 65000) {
				callback(new Error("送货数量不能大于65000公斤"));
			}
			callback()
		};
		let checkCabinetNo = (rule, value, callback) => {
      const str = value.toString();
      if (str.length === 11) {
        for (let i = 0; i < 11; i++) {
          const v = str[i];
          // 前4位验证为大写字母
          if (i < 4) {
            if (v < 'A' || v > 'Z') {
              callback(new Error("前4位为大写字母！"));
            }
          } else {
            // 后7位为数字
            if (v < '0' || v > '9') {
              callback(new Error("后7位为数字！"));
            }
          }
        }
        callback();
      } else {
        callback(new Error("请输入4位大写字母+7位数字！"));
      }
    };
    // 卡号验证
    let checkCartNo = (rule, value, callback) => {
      const str = value.toString();
      if (str.length === 7) {
        for (let i = 0; i < 7; i++) {
          const v = str[i];
          if (v < '0' || v > '9') {
            callback(new Error("卡号为7位数字！"));
          }
        }
        callback();
      } else {
        callback(new Error("7位数字的编号！"));
      }
    }
    // 柜号数量验证
    const checkCabinetQty = (rule, value, callback) => {
      if (
        Number(value) < 1 || Number(value) > 2 || 
        Number(value) != value || parseInt(value) != value
      ) {
        callback(new Error('请输入1-2的整数'));
      }
      callback();
    };
    // 卡号数量验证
    const checkCartQty = (rule, value, callback) => {
      if (
        Number(value) < 1 || Number(value) > 6 || 
        Number(value) != value || parseInt(value) != value
      ) {
        callback(new Error('请输入1-6的整数'));
      }
      callback();
    };

		return {

			carNum: "",                     //车号
			startDate: "",                 //开始日期
			endDate: "",                   //结束日期
			state: "",                     //状态

			queryDisabled: false,          //查询按钮可编辑
			appiontDisabled: false,        //预约按钮可编辑
			checkAppointDisabled: false,   //编辑按钮可编辑
			cancelAppointDisabled: false,  //取消按钮可编辑
			comfirmDisabled: false,        //保存按钮可编辑

			// 列表数据
			gridOptions: null,
			columnDefs: null,
			rowData: [],
			loading: false,

			// 分页
			currentPage: 1,                 //当前页
			pageSize: 30,                   //每页条数
			totalPage: 0,                   //总数

			//弹出框数据
			dialogTitle: "预约",             //标题
			dialogFormVisible: false,        //弹出框隐藏
			dialogEdit: false,               //隐藏输入框
			appointform: {
				deliveryNo: "",              //送货单号
				purchaseOrderNo: "",           //采购单号
				supplierCode: "",            //供应商代码
				supplierName: "",            //供应商名称
				batch: "",                    // 批次
				matName: "",                  // 物料名称
				companyName: "",             //送货公司
				companyCode: "",             //送货公司代码
				unloadingPlace: "",            //送货区域
				linkMan: "",                    //送货地点联系人
				carNum: "",                   //车号
				appointmentDate: "",             //预约日期
				appointmentPeriod: "",             //预约时段
				transport: "",              //运输方式
				cabinetType: "",            //柜型
				quantity: "",               //送货数量
				driver: "",                 //联系人
				driverPhone: "",               //联系电话

				cartQty: "",                 //卡数  
				cartNo1: "",                 //卡号1
				cartNo2: "",                 //卡号2
				cartNo3: "",                 //卡号3
				cartNo4: "",                 //卡号4
				cartNo5: "",                 //卡号5
				cartNo6: "",                 //卡号6
				cabinetQty: "",               //柜数                 
				cabinetNo1: "",              //柜号1                 
				cabinetNo2: "",              //柜号2          
			},
			maxAppointQtyList: [],           //最大可预约数
			appointStateItem: [              //状态数据
				{ code: "0", name: "未审批" },
				{ code: "1", name: "已通过" },
				{ code: "2", name: "已退回" },
				{ code: "3", name: "已到达" },
				{ code: "4", name: "已取消" },
				{ code: "5", name: "已卸完" },
			],
			remainQty: "",                    //剩余数量
			tempSearch: {},                   //暂存查询条件           
			deliverAreaItem: [],              //送货区域数据
			allDeliverAreas: [],
			appointTimeItem: [],              //预约时段数据
			areaLinkMans: [],                  //区域联系人下拉选项集合
			transportTypeItem: ["汽车", "铁路", '集装箱'],              //运输方式数据
			cabinetTypeItem: ["20HQ", "40HQ"],                //柜型数据
			rules: {
				deliveryNo: [
					{ required: true, message: "送货单号不能为空", trigger: "blur" }
				],
				purchaseOrderNo: [
					{ required: true, message: "采购订单不能为空", trigger: "blur" }
				],
				unloadingPlace: [
					{ required: true, message: "送货区域不能为空", trigger: "blur" }
				],
				linkMan: [
					{ required: true, message: "区域联系人不能为空", trigger: "blur" }
				],
				carNum: [
					{ required: true, message: "送货车号不能为空", trigger: "blur" },
					{ validator: checkCarNo, message: "请输入正确车号", trigger: "blur" }
				],
				appointmentDate: [
					{ required: true, message: "预约日期不能为空", trigger: "blur" }
				],
				appointmentPeriod: [
					{ required: true, message: "预约时段不能为空", trigger: "blur" }
				],
				transport: [
					{ required: true, message: "运输方式不能为空", trigger: "blur" }
				],
				cabinetType: [
					{ required: true, message: "柜型不能为空", trigger: "blur" }
				],
				cabinetQty: [
          { required: true, message: "柜号数量不能为空", trigger: "blur" },
          { validator: checkCabinetQty, trigger: ["blur","change"] }
				],
				cabinetNo1: [
					{ required: true, message: "柜号1不能为空", trigger: "blur" },
					{ required: true, validator: checkCabinetNo, trigger: ["blur","change"] }   //CBHU3202732
				],
				cabinetNo2: [
					{ required: true, message: "柜号2不能为空", trigger: "blur" },
					{ required: true, validator: checkCabinetNo, trigger: ["blur","change"] }
				],
				cartQty: [
          { required: true, message: "卡号数量不能为空", trigger: "blur" },
          { validator: checkCartQty, trigger: ["blur","change"] }
				],
				cartNo1: [
					{ required: true, message: "卡号1不能为空", trigger: "blur" },
          { validator: checkCartNo, trigger: ['change', 'blur'] },
				],
				cartNo2: [
					{ required: true, message: "卡号2不能为空", trigger: "blur" },
          { validator: checkCartNo, trigger: ['change', 'blur'] },
				],
				cartNo3: [
					{ required: true, message: "卡号3不能为空", trigger: "blur" },
          { validator: checkCartNo, trigger: ['change', 'blur'] },
				],
				cartNo4: [
					{ required: true, message: "卡号4不能为空", trigger: "blur" },
          { validator: checkCartNo, trigger: ['change', 'blur'] },
				],
				cartNo5: [
					{ required: true, message: "卡号5不能为空", trigger: "blur" },
          { validator: checkCartNo, trigger: ['change', 'blur'] },
				],
				cartNo6: [
					{ required: true, message: "卡号6不能为空", trigger: "blur" },
          { validator: checkCartNo, trigger: ['change', 'blur'] },
				],
				quantity: [
					{ required: true, message: "送货数量不能为空", trigger: "blur" },
					{ validator: checkQty, trigger: "blur" }
				],
				driver: [
					{ required: true, message: "联系人不能为空", trigger: "blur" },
					{ max: 50, message: '不能超过50个字符', trigger: ["blur","change"] }
				],
				driverPhone: [
					{ required: true, message: "联系电话不能为空", trigger: "blur" },
					{ validator: checkPhone, trigger: "blur" }
				],
			}

		}
	},

	beforeMount () {
		this.gridOptions = gridOptions()
		this.columnDefs = [
			{ headerName: "送货单号", field: "deliveryNo", width: 180, checkboxSelection: true, headerCheckboxSelection: true },
			{ headerName: "预约日期", field: "appointmentDate", width: 130 },
			{ headerName: "预约时段", field: "appointmentPeriod", width: 130 },
			{
				headerName: "申请日期",
				field: "createDate",
				width: 130,
				valueFormatter: params => {
					if (!params.value) {
						return this.$utils.dateFormat("yyyy-MM-dd", params.value)
					}
				}
			},
			{ headerName: "车号", field: "carNum", width: 130 },
			{ headerName: "送货数量", field: "quantity", width: 130 },
			{ headerName: "卡号/柜号", field: "cabinet", width: 130 },
			{ headerName: "采购订单", field: "purchaseOrderNo", width: 130 },
			{
				headerName: "状态",
				field: "state",
				width: 130,
				cellRenderer: params => {
					this.appointStateItem.forEach(item => {
						if (item.code == params.value) {
							params.value = item.name
						}
					})
					return params.value
				}
			},
			{ headerName: "运输方式", field: "transport", width: 130 },
			{ headerName: "司机", field: "driver", width: 130 },
			{ headerName: "司机电话", field: "driverPhone", width: 130 },
			{ headerName: "送货公司", field: "companyCode", width: 130 },
			{ headerName: "送货地点", field: "unloadingPlace", width: 130 },
			{ headerName: "创建日期", field: "createDate", width: 130 },
			{ headerName: "创建人", field: "creator", width: 130 }
		]

	},
	created () {
		this.queryAppointList(1)
	},
	methods: {
        /**
		 * @vuese
		 * 送货地点改变回调
         * @arg 参数为改变后的值
		*/
		addressChange (val, first) {
      this.transportTypeChange();
      this.queryAppointTime();
      if (!first){
        this.appointform.appointmentPeriod = ''
        this.appointform.linkMan = ''
      }
      this.areaLinkMans = this.allDeliverAreas.filter(item => {
        return val == item.unloadAddree
      })
		},
		/**
		 * @vuese
		 * 输入送货单获取送货单详情
		*/
		getPurOrderInfo (val) {
			let params = {
				deliveryNo2: this.appointform.deliveryNo,
				billState: 3,
				macType: 1
			}
      this.areaLinkMans = []
      this.purchaseOrderClear();
			_Api.getDeliveryDetail(params).then(res => {
				let data = res.data;
				if (data.code == 1 && data.rows) {
					let purOrderData = data.rows;
					// this.appointform.companyName = purOrderData.companyName;        //公司名称
					// this.appointform.companyCode = purOrderData.companyCode;        //公司代码
					// this.appointform.supplierName = purOrderData.supplierName;      //供应商名称
					// this.appointform.supplierCode = purOrderData.supplierCode;      //供应商代码
					// this.appointform.carNum = purOrderData.carNum;
					this.appointform.purchaseOrderNo = purOrderData.purOrdNo;       //采购订单
					this.purchaseOrderChange(purOrderData.purOrdNo);
					this.queryUnloadLocation(this.appointform.companyCode)        //查询卸货地点
					this.queryAppointTime()           //查询卸货时间段
				}
			})

		},
		//根据订单查询
		queryRemainQty (params) {
			let obj = {
				purchaseOrderNo: params
			}
			this.areaLinkMans = []
			this.$http.queryRemainQty(obj).then(res => {
				let data = res.data;
				this.deliverAreaItem = [];
				if (data.code == 1 && data.total > 0) {
					let originData = data.rows;
					this.appointform.batch = originData.batch;      //批次
					this.appointform.matName = originData.matName;      //物料名称
					this.appointform.supplierName = originData.supplierName;      //供应商
					this.appointform.supplierCode = originData.supplierCode;      //供应商代码
					this.appointform.companyName = originData.companyName;        //公司名称
					this.appointform.companyCode = originData.companyCode;        //公司代码
					this.queryUnloadLocation(this.appointform.companyCode)      //查询卸货地点
					this.queryAppointTime()         //查询预约时段
				} else {
					this.purchaseOrderClear();

				}
			}).catch(err => {
				this.purchaseOrderClear();
			})
		},
		//输入采购订单
		purchaseOrderChange (value) {
			this.queryRemainQty(value);
		},
		//清除采购订单
		purchaseOrderClear () {
			this.appointform.purchaseOrderNo = "";
			this.appointform.batch = "";
			this.appointform.matName = "";
			this.appointform.companyName = "";
			this.appointform.companyCode = "";
			this.appointform.supplierName = "";
			this.appointform.supplierCode = "";
			this.appointform.carNum = "";
		},

		//送货地点
		queryUnloadLocation (value) {
			let params = {
                companyCode:value,
                pageSize:10000,
                current:1
			}
      this.allDeliverAreas = [];
      this.deliverAreaItem = [];
			this.$http.queryUnloadLocation(params)
				.then(res => {
					let data = res.data;
					if (data.code == 1) {
            let originData = data.rows;
						let result = {};
						this.allDeliverAreas = originData
						for (let i = 0; i < originData.length; i++) {
							result[originData[i].unloadAddree] = originData[i];
						}
						for (let item in result) {
							this.deliverAreaItem.push(result[item]);
            }
            if (this.dialogTitle == "编辑" && this.appointform.unloadingPlace) {
              this.addressChange(this.appointform.unloadingPlace, true);
            } else {
              this.appointform.unloadingPlace = this.deliverAreaItem[0].unloadAddree;
              this.addressChange(this.appointform.unloadingPlace, true);
            }
					} else {
						this.$alert(data.info, {
							showClose: false,
							confirmButtonText: "确定",
							customClass: "alertFailure"
						});
					}
				})
				.catch((error) => {
				})
		},
		//获取时间段
		queryAppointTime () {
      this.appointTimeItem = [];
      if (!this.appointform.companyCode || !this.appointform.unloadingPlace) return;
			let params = {
        companyCode: this.appointform.companyCode,
        companyPlace: this.appointform.unloadingPlace,
        pageSize: 10000,
        current: 1,
			}
			this.$http.queryAppointTime(params)
				.then((res) => {
					let data = res.data;
					if (data.code == 1) {
						let originData = data.rows.splice(0);
						this.maxAppointQtyList = originData;
						this.appointTimeItem = originData.map(item => item.timeFrame);
					} else {
						this.maxAppointQtyList = [];
						this.$message({
							$message: data.info,
							type: "error"
						})
					}
				})
				.catch((err) => {
					this.maxAppointQtyList = [];
				})
		},

		//选择运输方式
		transportTypeChange () {
      const FORM_KEYS = [
        'companyCode',
        'appointmentPeriod',
        'transport',
        'appointmentDate',
        'unloadingPlace'
      ];
      for (const key of FORM_KEYS) {
        if (!this.appointform[key]) {
          return;
        }
      }

			let params = {
				companyCode: this.appointform.companyCode,   //公司
				period: this.appointform.appointmentPeriod,  //预约时段
				transport:  this.appointform.transport,      //运输方式
        appointTime: this.appointform.appointmentDate,  //预约日期   
        companyPlace: this.appointform.unloadingPlace //厂区
      }

			_Api.queryResidue(params).then(res => {
				let data = res.data;
				if (data.code == 1) {
					let originData = data.rows;
					if (originData <= 0) {
						this.remainQty = 0;
					} else {
						this.remainQty = originData;
					}
				} else {
					this.remainQty = "";
				}
			}).catch(error => {
				this.remainQty = "";
			})

		},
		//保存查询参数
		saveTempCondition () {
			this.tempSearch.carNum = this.carNum;
			this.tempSearch.startDate = this.startDate;
			this.tempSearch.endDate = this.endDate;
			this.tempSearch.state = this.state;
		},
		//获取查询参数
		getTempCondition () {
			this.carNum = this.tempSearch.carNum;
			this.startDate = this.tempSearch.startDate;
			this.endDate = this.tempSearch.endDate;
			this.state = this.tempSearch.state;
		},
		// 查询
		queryAppointList (type) {
			let params = {
				carNum: '',
				state: '',
				startDate: '',
				endDate: '',
				pageSize: this.pageSize,
				current: this.currentPage
			}
			if (this.carNum) {
				params.carNum = this.carNum;
			}
			if (this.state) {
				params.state = this.state;
			}
			if (this.startDate) {
				params.startDate = this.startDate;
			}
			if (this.endDate) {
				params.endDate = this.endDate;
      }
			if (this.endDate && this.endDate < this.startDate) {
				this.$alert("开始日期不能大于结束日期", {
					showClose: false,
					comfirmButton: "确定",
					customClass: "alertPrompt"
				})
				return
			}
			if (type === 1) {
				params.current = 1;
				this.currentPage = 1;
			}
			this.queryDisabled = true;
			this.loading = true;
			_Api.queryAppointLis(params).then(res => {
				this.saveTempCondition();
				this.queryDisabled = false;
				this.loading = false;
				let data = res.data;
				if (data.code == 1) {
					let originData = data.rows.splice(0);
					this.rowData = originData;
					this.totalPage = data.total;
				} else {
					this.rowData = [];
					this.totalPage = 0;
					that.$alert(data.info, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					});
				}
			}).catch(error => {
				this.loading = false;
				this.queryDisabled = false;
				this.$alert("查询失败,请检查网络", {
					showClose: false,
					comfirmButton: "确定",
					customClass: "alertFailure"
				})
			})
		},
		//选择分页重新回填数据
		paginationFillCondition (type) {
			this.getTempCondition();
			this.queryAppointList(type);
		},

		//条数变化
		handleSizeChange (value) {
			this.pageSize = value;
			this.paginationFillCondition(1);
		},
		//当前页变化
		handleCurrentChange (value) {
			this.currentPage = value;
			this.paginationFillCondition(0);
		},
		//向前一页
		handlePrevClick (value) {
			this.currentPage = value;
			this.paginationFillCondition(0);
		},
		//向后一页
		handleNextClick (value) {
			this.currentPage = value;
			this.paginationFillCondition(0);
		},

		rowDoubleClickedShow () { },
		// 预约
		addAppointList () {
      this.deliverAreaItem = [];
      this.allDeliverAreas = [];
      this.appointTimeItem = [];
      this.areaLinkMans = [];

      this.dialogFormVisible = true;
      this.appointform = {
				deliveryNo: "",              //送货单号
				purchaseOrderNo: "",           //采购单号
				supplierCode: "",            //供应商代码
				supplierName: "",            //供应商名称
				batch: "",                    //批次
				matName: "",                  //物料名称
				companyName: "",             //送货公司
				companyCode: "",             //送货公司代码
				unloadingPlace: "",            //送货区域
				linkMan: "",                    //送货地点联系人
				carNum: "",                   //车号
				appointmentDate: "",             //预约日期
				appointmentPeriod: "",             //预约时段
				transport: "",              //运输方式
				cabinetType: "",            //柜型
				quantity: "",               //送货数量
				driver: "",                 //联系人
				driverPhone: "",               //联系电话

				cartQty: "",                 //卡数  
				cartNo1: "",                 //卡号1
				cartNo2: "",                 //卡号2
				cartNo3: "",                 //卡号3
				cartNo4: "",                 //卡号4
				cartNo5: "",                 //卡号5
				cartNo6: "",                 //卡号6
				cabinetQty: "",               //柜数                 
				cabinetNo1: "",              //柜号1                 
				cabinetNo2: "",              //柜号2          
			}
			this.dialogTitle = "预约";
		},
		//取消预约
		dialogCancel () {
			this.$refs['appointform'].resetFields()
			setTimeout(() => {
				this.dialogFormVisible = false;
				this.maxAppointQtyList = [];
				this.remainQty = "";
			}, 100)

		},
		//编辑
		checkAppoint () {
			let selectRow = this.gridOptions.api.getSelectedRows();
			if (selectRow.length == 1) {
				// if (selectRow[0].state != 0) {
				// 	this.$alert("请确认当前状态为未审批", {
				// 		showClose: false,
				// 		confirmButtonText: "确定",
				// 		customClass: "alertPrompt"
				// 	})
				// 	return
				// }
				this.dialogFormVisible = true;
				this.dialogTitle = "编辑";
				this.appointform = { ...selectRow[0] };
				let cabinet = this.appointform.cabinet.split(",")
        this.queryUnloadLocation(this.appointform.companyCode)
        this.queryAppointTime()
        
				if (this.appointform.transport == "铁路") {
					this.$set(this.appointform, "cartQty", cabinet.length);
					this.$set(this.appointform, "cartNo1", cabinet[0]);
					this.$set(this.appointform, "cartNo2", cabinet[1]);
					this.$set(this.appointform, "cartNo3", cabinet[2]);
					this.$set(this.appointform, "cartNo4", cabinet[3]);
					this.$set(this.appointform, "cartNo5", cabinet[4]);
					this.$set(this.appointform, "cartNo6", cabinet[5]);
				} else if (this.appointform.transport == "集装箱") {
					this.$set(this.appointform, 'cabinetQty', cabinet.length);
					this.$set(this.appointform, 'cabinetNo1', cabinet[0]);
					this.$set(this.appointform, 'cabinetNo2', cabinet[1]);
				}
			} else if (selectRow.length > 1) {
				this.$alert("只能选择一行数据编辑", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
			} else {
				this.$alert("请选择要编辑的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
			}
		},
		/**
         * @vuese
         * 确认提交预约信息
        */
    dialogSubmit() {
      this.$refs['appointform'].validate((valid) => {
        if (valid) {
          this.dataSubmit();
        } else {
          return false;
        }
      });   
    },  
    dataSubmit() {
			let params = {
				appointmentDate: this.appointform.appointmentDate,       //预约日期
				appointmentMode: "",                                     //预约方式
				appointmentPeriod: this.appointform.appointmentPeriod,   //预约时段
				deliveryNo: this.appointform.deliveryNo,                  //送货单号
				carNum: this.appointform.carNum,                         //车号
				batch: this.appointform.batch,                            //批次
				matName: this.appointform.matName,                        //物料名称
				companyCode: this.appointform.companyCode,               //公司代码
				companyName: this.appointform.companyName,               //公司名称
				creator: this.$global.user.loginName,
				creatorId: this.$global.user.id,
				driver: this.appointform.driver,                        //联系人
				driverPhone: this.appointform.driverPhone,              //联系电话
				cabinetType: this.appointform.cabinetType,              //柜型
				modifyer: this.$global.user.loginName,
				modifyerId: this.$global.user.id,
				netWeight: 0,
				purchaseOrderNo: this.appointform.purchaseOrderNo,     //采购单号
				quantity: this.appointform.quantity,
				residueAmount: 0,
				supplierCode: this.appointform.supplierCode,          //供应商代码
				supplierName: this.appointform.supplierName,           //供应商名称
				tareWeight: 0,
				transport: this.appointform.transport,               //运输方式
				unloadingPlace: this.appointform.unloadingPlace,     //送货区域
				weighingWeight: 0,
				linkMan: this.appointform.linkMan
			}
			//卡号/柜号
			let cabinetData = ""
			if (this.appointform.cabinetQty == 1) {
				cabinetData = this.appointform.cabinetNo1;
			} else if (this.appointform.cabinetQty >= 2) {
				cabinetData = this.appointform.cabinetNo1 + "," + this.appointform.cabinetNo2
			} else if (this.appointform.cartQty == 1) {
				cabinetData = this.appointform.cartNo1
			} else if (this.appointform.cartQty == 2) {
				cabinetData = this.appointform.cartNo1 + "," + this.appointform.cartNo2
			} else if (this.appointform.cartQty == 3) {
				cabinetData = this.appointform.cartNo1 + "," + this.appointform.cartNo2 + "," + this.appointform.cartNo3
			} else if (this.appointform.cartQty == 4) {
				cabinetData = this.appointform.cartNo1 + "," + this.appointform.cartNo2 + "," + this.appointform.cartNo3 + "," + this.appointform.cartNo4
			} else if (this.appointform.cartQty == 5) {
				cabinetData = this.appointform.cartNo1 + "," + this.appointform.cartNo2 + "," + this.appointform.cartNo3 + "," + this.appointform.cartNo4 + "," + this.appointform.cartNo5
			} else if (this.appointform.cartQty >= 6) {
				cabinetData = this.appointform.cartNo1 + "," + this.appointform.cartNo2 + "," + this.appointform.cartNo3 + "," + this.appointform.cartNo4 + "," + this.appointform.cartNo5 + "," + this.appointform.cartNo6
			} else {
				params.cabinet = [""]
			}
			params.cabinet = [cabinetData]
			if (this.dialogTitle == "预约") {
				if (this.remainQty == 0) {
					this.$alert('剩余可预约数量0', {
						showClose: false,
						confirmButtonText: "确定",
						customClass: "alertPrompt"
					})
					return;
				}
				this.appiontDisabled = true;
				this.comfirmDisabled = true;
				_Api.saveAppointLis(params).then(res => {
					let data = res.data;
					this.appiontDisabled = false;
					this.comfirmDisabled = false;
					if (data.code == 1) {
					  this.dialogFormVisible = false;
						this.$message({
							message: data.info,
							type: "success"
						})
						this.appointform = {};
						this.maxAppointQtyList = [];
						this.remainQty = "";
						this.queryAppointList(0);
					} else {
						this.$alert(data.info, {
							showClose: false,
							confirmButtonText: "确定",
							customClass: "alertFailure"
						});
					}
				}).catch(error => {
					this.appiontDisabled = false;
					this.comfirmDisabled = false;
					this.$alert(error.data.info, {
						showClose: false,
						confirmButtonText: "确定",
						customClass: "alertFailure"
					});
				})
			} else if (this.dialogTitle == "编辑") {
				params.id = this.appointform.id;
				this.checkAppointDisabled = true;
				this.comfirmDisabled = true;
				_Api.editAppointLis(params).then(res => {
					this.dialogFormVisible = false;
					this.checkAppointDisabled = false;
					this.comfirmDisabled = false;
					let data = res.data;
					if (data.code == 1) {
					  this.dialogFormVisible = false;
						this.$message({
							message: data.info,
							type: "success"
						})
						this.appointform = {};
						this.queryAppointList(0);
					} else {
						this.$alert(data.info, {
							showClose: false,
							confirmButtonText: "确定",
							customClass: "alertFailure"
						});
					}
				}).catch(error => {
					this.checkAppointDisabled = false;
					this.comfirmDisabled = false;
					this.$alert(error.data.info, {
						confirmButtonText: "确定",
						customClass: "alertFailure"
					})

				})
			}
		},

		//取消
		cancelAppoint () {
			let cancelAppointSelectRow = this.gridOptions.api.getSelectedRows();
			let stateData = true;
			let ids = [];
			if (cancelAppointSelectRow.length >= 1) {
				cancelAppointSelectRow.forEach(item => {
					ids.push(item.id);
					if (item.state != 0) {
						return stateData = false
					}
				})
				if (stateData == false) {
					this.$alert("只能取消未审批状态数据", {
						showClose: false,
						confirmButtonText: "确定",
						customClass: "alertPrompt"
					})
					return
				}
			} else {
				this.$alert("请选择要取消的数据", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				return
			}

      this.$confirm('确定要取消该数据吗？').then(_ => {
        let params = {
          confirmer: this.$global.user.loginName,
          confirmerId: this.$global.user.id,
          ids: ids,
          state: 3
        }
        this.cancelAppointDisabled = true;
        _Api.cancelAppoint(params).then(res => {
          this.cancelAppointDisabled = false;
          let data = res.data;
          if (data.code == 1) {
            this.queryAppointList(0);
            this.$message({
              message: data.info,
              type: "success"
            })
          } else {
            this.$alert(data.info, {
              showClose: false,
              confirmButtonText: "确定",
              customClass: "alertFailure"
            })
          }
        }).catch(error => {
          this.cancelAppointDisabled = false;
          this.$alert("取消失败,请检查网络", {
            showClose: false,
            confirmButtonText: "确定",
            customClass: "alertFailure"
          })
        })
      })
      .catch(_ => {})
    },
    
    // 集装箱柜型改变
    cabinetTypeChange(val) {
      if (val == '40HQ') {
        this.$set(this.appointform, 'cabinetQty', 1);
      }
    }
	}
}
</script>

<style lang="less" >
.m-view-appointmentListS {
	.el-row {
		line-height: 30px;
		.el-form-item {
			margin-bottom: 18px;
		}
	}
	.m-agTable {
		top: 50px;
		.ag-table {
			position: absolute;
			left: 0;
			right: 0;
			bottom: 0;
			top: 0;
		}
	}
	.m-appointDialog {
		//   height: 700px;
		.m-appointFormDialog {
			height: 450px;
			overflow-x: hidden;
			overflow-y: auto;
			.el-row {
				height: 48px;
				//   line-height: 48px ;
				padding-right: 10px;
			}
		}
	}
}
</style>